package us.versus.them.bitly;

import flash.display.BitmapData;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.text.TextField;

import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;

class Pavg implements Bitter {
	var sum : Float;
	var mask : Array< Array< Float > >;

	public function new() {
	}

	public function reset( w:Int, h:Int, bitmapData:BitmapData, tmp:BitmapData ) {
		var m = Math;
		for ( y in 0 ... h ) {
			for ( x in 0 ... w ) {
				bitmapData.setPixel( x, y, m.floor( 0xFFFFFF * m.random() ) );
			}
		}

		var leMode = m.floor( m.random() * 2 );

		var r;
		mask = new Array< Array< Float > >();
		sum = 0;
		for ( i in 0 ... 3 ) {
			mask[ i ] = new Array< Float >();
			for ( j in 0 ... 3 ) {
				switch( leMode ) {
					//case 1: r = 1 - m.random() * 2;
					case 1: r = -m.random();
					default: r = m.random();
				}
				sum += r;
				mask[ i ].push( r );
			}
		}
		//sum = 1 - m.random() * 2;
		if ( 0 == sum ) sum = 1;
	}

	public function loop( w:Int, h:Int, bitmapData:BitmapData, tmp:BitmapData ) : Bool {
		var m = Math;
		for ( y in 0 ... h ) {
			for ( x in 0 ... w ) {
				var value = 0.0;
				for ( i in 0 ... 3 ) {
					for ( j in 0 ... 3 ) {
						value += (
							App.pixelAt( x + j - 1, y + i - 1, w, h,  bitmapData )
							* 
							mask[ i ][ j ] 
						);
					}
				}
				tmp.setPixel( x, y, m.floor( value / sum ) );
			}
		}
		return true;
	}


}
